package com.hk.core.authentication.security.authentication.verifycode;

import com.hk.core.authentication.api.validatecode.image.ImageCode;
import com.hk.core.authentication.api.validatecode.image.ImageCodeProcessor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 用户名，密码，加验证码登录
 * <p>
 * 登录时需要加4个参数:
 * verifyRequestId:
 * verifyCode:
 * username:
 * password:
 */
@Setter
@RequiredArgsConstructor
public class VerifyCodeUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public static final String VERIFY_CODE_REQUEST_ID = "verifyRequestId";

    public static final String VERIFY_CODE_CODE = "verifyCode";

    private String verifyCodeRequestId = VERIFY_CODE_REQUEST_ID;

    private String verifyCodeParamName = VERIFY_CODE_CODE;

    private final ImageCodeProcessor imageCodeProcessor;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String requestId = request.getParameter(verifyCodeRequestId);
        String verifyCode = request.getParameter(verifyCodeParamName);
        imageCodeProcessor.validate(new ImageCode().setCode(verifyCode).setId(requestId));
        return super.attemptAuthentication(request, response);
    }
}
